/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package service;

import dao.UserDAO;
import Entity.User;
import java.util.List;
import javax.persistence.Query;
import javax.persistence.EntityManager;
import VO.UserVO;

/**
 *
 * @author Edwin
 */
public class UserService {
    private UserDAO userDAO;

    public UserService() {
        userDAO = new UserDAO();
    }
    
    public void persistUser(UserVO vo, EntityManager em){
        User entityAdmin = new User();
        entityAdmin.setId(vo.getId());
        entityAdmin.setLogin(vo.getLogin());
        entityAdmin.setNameUser(vo.getNameUser());
        entityAdmin.setPassword(vo.getPassword());
        
        UserDAO.persistAdmin(entityAdmin, em);
    }
    
    
    
    public User convertToEntityUser(UserVO adminVO){
        User entity = new User();
        entity.setId(adminVO.getId());
        entity.setLogin(adminVO.getLogin());
        entity.setNameUser(adminVO.getNameUser());
        entity.setPassword(adminVO.getPassword());
        
        return entity;
    }
    
    
    
    
    public UserVO correctLoginUser(UserVO vo, EntityManager em){
        User entityAdmin = new User();
        entityAdmin=convertToEntityUser(vo);
        int countLogin=0,countPassword=0;
        String copyLogin=entityAdmin.getLogin();
        String copyPassword=entityAdmin.getPassword();
        /**
         * aqui se hace una una validación de los datos 
         * de login ingresados en la vista 
         * si estan bien escritos
         */
         if(copyLogin!=null && copyPassword != null){
             countLogin=countCharacter(copyLogin);
             countPassword=countCharacter(copyPassword);
             if(countLogin==copyLogin.length()&&countPassword==copyPassword.length()){
                 entityAdmin=userDAO.correctLoginAdmin(entityAdmin, em);
             }
         }
         if (entityAdmin!=null)
             return entityAdmin.toVO(entityAdmin);
         else 
             return null;
         
    }
    
    public int countCharacter(String copy){
        int count=0;
        if(copy==null){
            return 0;
        }else{
            for(int i=0;i<copy.length();i++){
                if((copy.charAt(i)>=48 && copy.charAt(i)<=57)||
                        (copy.charAt(i)>=65 && copy.charAt(i)<=90)||
                        (copy.charAt(i)>=97 && copy.charAt(i)<=122))
                    count++;
                else 
                    break;
            }
        }
        return count;
    }
    
    
    
     
    public List<User> getUserList(EntityManager em){
        return userDAO.getUserList(em);
    }
}